package com.liangzhen.verynews.data;

import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.liangzhen.verynews.bean.Game;

public class ParseNewsGame {
	
	private ArrayList<Game> newslist = new ArrayList<Game>();

	public static JSONObject ParseJson(final String path, final String encode) {

		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost("http://appapi.very-news.com/moreNews.m?pull_type=down&channel=play&sort_time=0&version_name=1.2.1&start_count=1&udid=E6BA61777016BE968AEFEA9FB9A065EB&uid=");
		try {
			HttpResponse httpResponse = httpClient.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity(),
						encode);
				JSONObject jsonObject = new JSONObject(result);
				
				return jsonObject;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpClient != null)
				httpClient.getConnectionManager().shutdown();
		}
		return null;
	}

	public ArrayList<Game> getNewsList(String path) {
		JSONObject json = ParseNewsGame.ParseJson(path, "utf-8");
		try {
			int channel = json.getInt("channel_sequence");
			JSONArray news = json.getJSONArray("news");
			Game game = new Game();
			for (int i = 1; i < news.length(); i++) {
				
				JSONObject gameItem = news.getJSONObject(i);
				System.out.println("--->" + news.length());
				game.setTitle(gameItem.getString("title"));
				
				String title = gameItem.getString("title");
				System.out.println("---------->" + title);
				System.out.println("--->" + news.length());
				game.setSource(gameItem.getString("source"));
				game.setNid(gameItem.getString("nid"));
				game.setImageUrl(gameItem.getString("imageUrl"));
				newslist.add(game);
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return newslist;
	}
}
